package com.sdry.web.controller.llm;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.security.auth.login.LoginException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.sdry.model.llm.Classes;
import com.sdry.model.llm.Department;
import com.sdry.model.llm.EmployeeRecord;
import com.sdry.model.llm.Menu;
import com.sdry.model.llm.Permission;
import com.sdry.model.llm.Role;
import com.sdry.model.llm.Team;
import com.sdry.model.llm.TeamRecord;
import com.sdry.model.llm.User;
import com.sdry.service.llm.ClassesService;
import com.sdry.service.llm.DepartmentService;
import com.sdry.service.llm.EmployeeRecordService;
import com.sdry.service.llm.PermissionService;
import com.sdry.service.llm.TeamRecordService;
import com.sdry.service.llm.TeamService;
import com.sdry.service.llm.UserService;
import com.sdry.utils.MD5;

/** 
* 登陆
* @author lian 
* @version 1.0
* @time 2018年10月17日 上午12:44:08
*/

@Controller
public class LoginController {
	
	/**
	 * 用户信息
	 */
	private User temp = new User();
	
	/*注入用户service*/
	@Resource
	private UserService userService; 
	/*注入资源service*/
	@Resource
	private PermissionService permissionService; 
	/*注入班组记录service*/
	@Resource
	private TeamRecordService teamRecordService; 
	/*注入班组记录service*/
	@Resource
	private EmployeeRecordService employeeRecordService;
	/*注入班组service*/
	@Resource
	private TeamService teamService; 
	/*注入部门service*/
	@Resource
	private DepartmentService depService;
	/*注入班次service*/
	@Resource
	private ClassesService classesService;
	
	/**
	 * 登陆
	 * @param session
	 * @param user
	 * @return
	 * @throws LoginException
	 */
	@RequestMapping("/login")
	public ModelAndView login(HttpSession session,User user, String position, HttpServletRequest request) throws LoginException{
		ModelAndView mv = new ModelAndView();
		//1、如果账号或是密码为空，还在登陆页面
		if("".equals(user.getAccount()) || "".equals(user.getAccount())  || null == user.getAccount() || null == user.getPassword()){
			mv.setViewName("/llm/login");
			mv.addObject("message","账号或密码为空,请重新输入");
		}else{
			//1、根据账号密码，获取用户信息
			user.setPassword(MD5.md5Encode(user.getPassword()));
			temp = userService.login(user);
			//2、账号密码正确
			if(temp != null && !"".equals(temp)){
				logOut(session);
				//把部门信息存入session
				Department department = depService.getDepartmentByDid(Long.parseLong(temp.getDepName()));
				session.setAttribute("department", department);
				//把班组信息存入session
				Team team = teamService.getTeamByUid(temp.getUid());
				session.setAttribute("team", team);
				//把用户信息存入session
				session.setAttribute("currentUser", temp);
				Date date = new Date();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String today = sdf.format(date);
				//当天的小时
				Integer hourse = Integer.parseInt(today.substring(11, 13));
				if(null != temp){
					List<Classes> classesByName = classesService.getClassesByName("白班");
					Classes cla = classesByName.get(0);
					//白班的开始时间（小时） 
					Integer startTime = Integer.parseInt(cla.getStartTime().substring(0,2));
					//如果登录时间小于当天的白班的开始时间，则记录上一天
					if(hourse < startTime){
						Calendar ca = Calendar.getInstance();//得到一个Calendar的实例 
						ca.setTime(date); //设置时间为当前时间
						ca.add(Calendar.DATE, -1);
						Date last = ca.getTime();
						today = sdf.format(last);
					}
					temp.setRemark3(today.substring(0, 10));
				}
				//session无操作保存多久，单位秒
				session.setMaxInactiveInterval(12*60*60);
				//3、如果有选择登录界面
				if(null != position && !"".equals(position)){
					//3.1、生产工位登录
					if("膜丝".equals(position) || "组装".equals(position) || "离心".equals(position) || "拆端盖".equals(position) || "固化".equals(position) || "切割".equals(position)){
						if(null != team){
							TeamRecord teamRecord = teamRecordService.getTeamRecordByTeamAndTime(team.getTid(), today);
							if(null != teamRecord){
								List<Classes> classess = classesService.getClassesByName(teamRecord.getRemark01());
								Classes clas = classess.get(0);
								//班次的开始时间（小时） 
								Integer startTime = Integer.parseInt(clas.getStartTime().substring(0,2));
								//班次的开始时间（小时） 
								Integer endTime = Integer.parseInt(clas.getEndTime().substring(0,2));
								Boolean bo = false;
								//如果开始时间和结束时间在同一天
								if(startTime < endTime){
									if(startTime <= hourse && hourse < endTime){
										bo = true;
									}
								}else{
									if(startTime <= hourse || hourse < endTime){
										bo = true;
									}
								}
								//如果在工作时间内登录
								if(bo){
									//把工位信息和员工姓名存入班组记录表的班组人员列中(班组记录版本2)
									int isSuccess = employeeRecordService.saveEmployeeRecord(position, temp.getAccount(), team.getTid(), session);
									if(isSuccess > 0){
										//选择工位
										switch (position) {
										case "膜丝":
											mv.setViewName("forward:/jumpPage/w1.do");
											break;
										case "组装":
											mv.setViewName("forward:/jumpPage/w2.do");
											break;
										case "拆端盖":
											mv.setViewName("forward:/jumpPage/w4.do");
											break;
										case "固化":
											mv.setViewName("forward:/jumpPage/w42.do");
											break;
										case "离心":
											mv.setViewName("forward:/jumpPage/w3.do");
											break;
										case "切割":
											mv.setViewName("forward:/jumpPage/w5.do");
											break;
										default:
											mv.setViewName("/llm/login");
											mv.addObject("message","重新选择工位,请重新输入");
											break;
										}
									}else{
										mv.setViewName("/llm/login");
										mv.addObject("message","班组长还没有选择排产单，请稍后登录");
									}
								}else{
									mv.setViewName("/llm/login");
									mv.addObject("message","非工作时间，禁止登录");
								}
							}else{
								mv.setViewName("/llm/login");
								mv.addObject("message","非工作时间，禁止登录");
							}
						}else{
							mv.setViewName("/llm/login");
							mv.addObject("message","不能选择工位,请重新输入");
						}
					}
					//3.2、质检工位登录				
					if("检漏".equals(position) || "组件评价".equals(position) || "气密性检测".equals(position)){
						String str = "/llm/login";
						List<Permission> permissionList = userService.getPermissionByUid(temp.getUid());
						//选择工位
						switch (position) {
						case "检漏":
							for(Permission permission : permissionList){
								if("检漏".equals(permission.getName())){
									str = "forward:/leakHunting/enterLeakHuntingPage.do";
								}
							}
							mv.setViewName(str);
							if(str.equals("/llm/login")){
								mv.addObject("message","没有质检权限，请重新选择工位");
							}
							break;
						case "组件评价":
							for(Permission permission : permissionList){
								if("组件评价".equals(permission.getName())){
									str = "forward:/evaluate/enterEvaluatePage.do";
								}
							}
							mv.setViewName(str);
							if(str.equals("/llm/login")){
								mv.addObject("message","没有质检权限，请重新选择工位");
							}
							break;
						case "气密性检测":
							for(Permission permission : permissionList){
								if("气密性检测".equals(permission.getName())){
									str = "forward:/gas/enterGasPage.do";
								}
							}
							mv.setViewName(str);
							if(str.equals("/llm/login")){
								mv.addObject("message","没有质检权限，请重新选择工位");
							}
							break;
						default:
							mv.setViewName("/llm/login");
							mv.addObject("message","重新选择工位,请重新输入");
							break;
						}
					}
				//否则直接跳转首页（没有工位信息，则不是员工登陆，是班组长或其他用户）
				}else{
					//3、根据用户ID获取菜单权限
					List<Menu> menus = permissionService.findByUserId(temp.getUid());
					session.setAttribute("menus", menus);
					if(menus.size() > 0){
						mv.setViewName("/llm/index");
					}else{
						mv.setViewName("/llm/login");
						mv.addObject("message","没有权限,请重新输入");
					}
				}
			//2、账号密码错误
			}else{
				mv.setViewName("/llm/login");
				mv.addObject("message","账号或密码错误,请重新输入");
			}
		}
		return mv;
	}
	
	/**
	 * 登出
	 * @param session
	 * @return
	 * @throws LoginException
	 */
	@RequestMapping("/logout")
	public String logOut(HttpSession session) throws LoginException{
		//把登出时间添加到最后一条记录中
		Date date = new Date();
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String logoutTime = sdf2.format(date);
		EmployeeRecord employeeRecord = new EmployeeRecord();
		employeeRecord.setLogoutTime(logoutTime);
		//获取用户登录后保存的员工记录的ID
		Object obj = session.getAttribute("employeeRecordId");
		if(null != obj && !"".equals(obj)){
			int id = (Integer)obj;
			Long id2 = id + 0L;
			employeeRecord.setId(id2);
			//根据ID修改登出时间
			employeeRecordService.updatelogoutTimeByEmployeeRecord(employeeRecord);
		}
		return "/llm/login";
	}
	
	
	/**
	 * APP登陆接口
	 * @param session
	 * @param user
	 * @return
	 * @throws LoginException
	 */
	@RequestMapping(value = "/appLogin")
	@ResponseBody
	public Object appLogin(String account,String password, HttpSession session) throws LoginException{
		//System.out.println(user);
		User user = new User();
		user.setAccount(account);
		user.setPassword(password);
		//根据账号密码，获取用户信息
		user.setPassword(MD5.md5Encode(user.getPassword()));
		User temp = userService.login(user);
		//账号密码正确
		if(temp != null && !"".equals(temp)){
			Map<Object, Object> map = new HashMap<>();
			map.put("state", "1");
			map.put("message", "登陆成功");
			// 根据用户ID查角色
			List<Role> roleByUser = userService.getRoleIdByUserId(temp.getUid());
			for(Role rb : roleByUser){
				if("SHE主管".equals(rb.getName())){
					temp.setRemark1(rb.getName());
				}
				if("质检员".equals(rb.getName())){
					temp.setRemark2(rb.getName());
				}
			}
			map.put("data", temp);
			return map;
		//错误
		}else{
			Map<String, String> map = new HashMap<>();
			map.put("state", "0");
			map.put("message", "登陆失败");
			map.put("data", "用户名或密码错误");
			return map;
		}
	}
	
	/**
	 * APP退出接口
	 * @param session
	 * @param user
	 * @return
	 * @throws LoginException
	 */
	@RequestMapping(value = "/appLogout")
	@ResponseBody
	public Object appLoginOut( HttpSession session) throws LoginException{
		session.removeAttribute("currentUser");
		Map<String, String> map = new HashMap<>();
		map.put("state", "1");
		map.put("message", "退出成功");
		return map;
	}
	
	@RequestMapping(value="/toLoginPage")
	public ModelAndView toLoginPage(){
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/llm/login");
		return mv;
	}
}
